package sort;

/**
 * @author wcj
 * @Date 2021/7/7 1:27
 * @Version 1.0
 */
public class MergeSort {

    /**
     * 归并排序：分治思想
     *
     * @param arr
     * @return
     */
    public static int[] mergeSort(int[] arr) {
        divide(arr, 0, arr.length - 1);
        return arr;
    }

    public static void divide(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = (left + right) / 2;
        divide(arr, left, mid);
        divide(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }

    public static void merge(int[] arr, int left, int mid, int right) {
        int[] helper = new int[right - left + 1];
        int p1 = left;
        int p2 = mid + 1;
        int k = 0;
        while (p1 <= mid && p2 <= right) {
            helper[k++] = arr[p1] > arr[p2] ? arr[p2++] : arr[p1++];
        }
        while (p1 <= mid) {
            helper[k++] = arr[p1++];
        }
        while (p2 <= right) {
            helper[k++] = arr[p2++];
        }
        for (int i = 0; i < helper.length; i++) {
            arr[left + i] = helper[i];
        }
    }
}
